﻿using Framework;

namespace Game
{
    public class PreloadGameResourcesActionable : IBTreeActionable<StartBTreeContext>
    {
        private int _semaphore = 0;
        
        public void OnStart(StartBTreeContext context)
        {
            int preloadCount = context.preloadResourcesList.Count;
            _semaphore = preloadCount;
            for (int i = 0; i < preloadCount; ++i)
            {
                ResManager.Instance.Load(context.preloadResourcesList[i], OnResLoadCompleted);
            }
        }

        public void OnEnd(StartBTreeContext context)
        {
        }

        public TaskStatus Update(StartBTreeContext context)
        {
            if (_semaphore > 0)
            {
                return TaskStatus.Running;
            }
            return TaskStatus.Success;
        }

        private void OnResLoadCompleted(Resource resource)
        {
            --_semaphore;
            resource.Retain();
        }
    }
}